package cn.lzd.mr.case6;

import cn.lzd.mr.PathUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Created by lzd on 2018/6/4.
 */
public class Case6MR2 {

    public static class Mp extends Mapper<LongWritable, Text, Text, Text> {

        Text k = new Text();
        Text v = new Text();

        /*
            将所有用户+用户的排重，拿到它们共有的朋友
         */
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
                throws IOException, InterruptedException {
            String[] split = value.toString().split("\t");
            k.set(split[0]);
            v.set(split[1]);
            context.write(k, v);

        }
    }

    /*
        遍历每对用户下所有朋友，将这些朋友拼接起来，输出。
     */
    public static class Rd extends Reducer<Text, Text, Text, Text> {
        Text v = new Text();

        @Override
        protected void reduce(Text friendGroup, Iterable<Text> commonFriend, Reducer<Text, Text, Text, Text>.Context context)
                throws IOException, InterruptedException {

            StringBuilder sb = new StringBuilder();
            for (Text cf : commonFriend) {

                sb.append(cf.toString()).append(" ");
            }
            v.set(sb.toString());
            context.write(friendGroup, v);
        }
    }


    public static void main(String[] args) throws Exception {

        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf);

        job.setJarByClass(Case6MR2.class);

        job.setMapperClass(Mp.class);
        job.setReducerClass(Rd.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.addInputPath(job, new Path(PathUtil.getpath("case6") + "text2"));
        FileOutputFormat.setOutputPath(job, new Path(PathUtil.getpath("case6") + "out2/"));


        job.waitForCompletion(true);

    }
}
